<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
	 <meta charset="utf-8">
	 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	 <title th:replace="common/base::pagetitle"></title>
	 <link th:replace="common/base::static"/>
</head>
<body style="background-color: #f2f2f2;">

<div id="kPage" class="layui-fluid" style="padding: 0">
	 <div class="layui-row">
		  <!-- 主要内容块 -->
		  <div class="layui-col-md12" id="kMainContentCol">
				<div class="layui-fluid wlb-fluid-padding15">
					 <div class="layui-card">
						  <form>
								<div class="layui-form layui-card-header wlb-card-header-auto">
									 <div class="layui-form-item">
										  <div class="layui-inline">
												<label class="layui-form-label">凭证编号</label>
												<div class="layui-input-inline">
													 <input type="text" name="id" placeholder="请输入" autocomplete="off" class="layui-input">
												</div>
										  </div>
										  <div class="layui-inline">
												<label class="layui-form-label">合同编号</label>
												<div class="layui-input-inline">
													 <input type="text" name="contractNo" placeholder="请输入" autocomplete="off" class="layui-input">
												</div>
										  </div>
										  <div shiro:hasAnyRoles="admin, core" class="layui-inline">
												<label class="layui-form-label">供应商</label>
												<div class="layui-input-inline">
													 <select name="supplierId" class="form-control" >
														  <option value="">请选择供应商</option>
														  <option th:each="supplier:${supplierList}" th:value="${supplier.id}" th:text="${supplier.name}"></option>
													 </select>
												</div>
										  </div>
										  <div shiro:hasAnyRoles="admin, supplier" class="layui-inline">
												<label class="layui-form-label">核心企业</label>
												<div class="layui-input-inline">
													 <select name="coreEnterpriseId" class="form-control" >
														  <option value="">请选择核心企业</option>
														  <option th:each="core:${coreList}" th:value="${core.id}" th:text="${core.name}"></option>
													 </select>
												</div>
										  </div>
<!--										  <div shiro:hasAnyRoles="admin" class="layui-inline">-->
<!--												<label class="layui-form-label">归属行</label>-->
<!--												<div class="layui-input-inline">-->
<!--													 <select name="bankId" class="form-control" >-->
<!--														  <option value="">请选择归属行</option>-->
<!--														  <option th:each="bank:${bankList}" th:value="${bank.id}" th:text="${bank.name}"></option>-->
<!--													 </select>-->
<!--												</div>-->
<!--										  </div>-->
<!--										  <div class="layui-inline">-->
<!--												<label class="layui-form-label">状态</label>-->
<!--												<div class="layui-input-inline">-->
<!--													 <select name="status" id="status" class="form-control" xm-select="status" xm-select-skin="normal">-->
<!--														  <option value="">请选择状态</option>-->
<!--														  <option th:each="dict:${dictList}" th:value="${dict.code}" th:text="${dict.name}"></option>-->
<!--													 </select>-->
<!--												</div>-->
<!--										  </div>-->
										  <div class="layui-inline">
												<label class="layui-form-label">生成时间</label>
												<div class="layui-input-inline">
													 <input type="text" id="createDate" name="createDate" placeholder="请选择生成时间" autocomplete="off" class="layui-input">
												</div>
										  </div>
<!--										  <div class="layui-form-item layui-hide">-->
<!--												<input type="text" id="status" name="status" value="11" placeholder="保存ID" autocomplete="off" class="layui-input">-->
<!--										  </div>-->
										  <div class="layui-inline">
												<button class="layui-btn " lay-submit="" lay-filter="kTableSearchFilter">
													 <i class="layui-icon layui-icon-search"></i>
												</button>
												<button class="layui-btn " type="reset">
													 <i class="layui-icon layui-icon-refresh-1"></i>
												</button>
										  </div>
									 </div>
								</div>
						  </form>
						  
						  <div class="layui-card-body">
								<table id="kContentTable" lay-filter="kContentTable"></table>
						  </div>
					 </div>
				
				</div>
		  </div>
	 </div>
</div>

<script th:replace="common/base::context"></script>
<script th:replace="common/base::mainjs"></script>

<script type="text/html" id="coreEnterpriseIdTpl">
	 {{# var data = wlbKit.get(api.sys.getDept + d.coreEnterpriseId).data; }}
	 {{# return data ? data.name : '<span class="layui-badge-rim">未分配</span>'; }}
</script>
<script type="text/html" id="supplierIdTpl">
	 {{# var data = wlbKit.get(api.sys.getDept + d.supplierId).data; }}
	 {{# return data ? data.name : '<span class="layui-badge-rim">未分配</span>'; }}
</script>
<script type="text/html" id="bankIdTpl">
	 {{# var data = wlbKit.get(api.sys.getDept + d.bankId).data; }}
	 {{# return data ? data.name : '<span class="layui-badge-rim">未分配</span>'; }}
</script>
<script type="text/html" id="statusTpl">
	 {{# var data = wlbKit.get(api.sys.dictGetByCode + d.status).data; }}
	 {{# return data ? data.name : '<span class="layui-badge-rim">未知</span>'; }}
</script>

<!--头部工具栏模板-->
<script type="text/html" id="headToolbarTpl">
</script>

<!--表格行工具栏模板-->
<script type="text/html" id="rowToolbarTpl">
	 <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>详情</a>
	 {{#  if(d.status == '11'){ }}
	 <!--平台审核-->
	 <a shiro:hasAnyRoles="admin,platform" shiro:hasPermission="voucher:audit" class="layui-btn layui-btn-xs" lay-event="audit"><i class="layui-icon layui-icon-release"></i>审核</a>
	 {{# } }}
</script>

<script type="text/javascript" th:inline="javascript">
    layui.use(['element', 'form', 'layer', 'table','formSelects','laydate'], function () {
        var elemet = layui.element, form = layui.form, layer = layui.layer, table = layui.table, formSelects = layui.formSelects, laydate = layui.laydate;
        var tableId = 'kContentTable';

        laydate.render({
            elem: '#createDate' //指定元素
            //,type: 'date' //默认，可不填
            , format: 'yyyy-MM-dd'
        });

        // 实例化table
        var tableIns = table.render($.extend(config.layui.table, {
            elem: '#' + tableId
            , url: BASE_WEB + 'voucher/list/data' //数据接口
            //, toolbar: '#headToolbarTpl'
				, where: {'status': '11'}
            , cols: [[ //表头
                {type: 'checkbox', fixed: 'left'}
                , {field: 'id', title: '凭证编号', width: 150}
                , {field: 'templateId', title: '模板id', hide: true, width: 120}
                , {field: 'contractNo', title: '合同编号', width: 120}
                , {field: 'voucherAmount', title: '凭证金额', width: 100}
                , {field: 'coreEnterpriseId', title: '核心企业',  width: 120, templet: '#coreEnterpriseIdTpl'}
                , {field: 'supplierId', title: '供应商', width: 120, templet: '#supplierIdTpl'}
                , {field: 'bankId', title: '银行', width: 120, templet: function (d){
								if (d.bankId != null && d.bankId != ''){
									 var data = wlbKit.get(api.sys.getDept + d.bankId).data;
									 return data ? data.name : '<span class="layui-badge-rim">未知</span>'
								}else{
								    return '<span class="layui-badge-rim">未分配</span>';
								}
						  }}
                , {field: 'signFlowId', title: '签章流程ID', width: 120}
                , {field: 'status', title: '状态', width: 140, templet: '#statusTpl'}
                , {field: 'createDate', title: '生成时间', sort: true, width: 180}
                , {field: 'updateDate', title: '更新时间', sort: true, width: 180}
                , {field: '', title: '操作', width: 235, fixed: 'right', templet: '#rowToolbarTpl'}
            ]]
				,done: function (res, curr, count){
    				var that = this.elem.next();
    				res.data.forEach(function (item, index){
						 if ("04" == item.status) {
						     var tr = that.find(".layui-table-box tbody tr[data-index='"+index+"']").find("td[data-field='status']").css("color", "#ff3300");
						 }else if("90" == item.status){
                       var tr = that.find(".layui-table-box tbody tr[data-index='"+index+"']").find("td[data-field='status']").css("color", "#66cc33");
						 }
					})
				}
		  }));

        var area = ['80%', '60%'];


        // 表格行按钮 监听事件
        table.on('tool(' + tableId + ')', function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            if (layEvent === 'edit') {
                layer.open({
                    type: 2
                    , title: '详情'
                    //, content: BASE_WEB + 'voucher/detail' + '?id=' + data.id
                    , content: BASE_WEB + 'data/preview' + '?id=' + data.id + '&templateId=' + data.templateId + '&url=voucher/get'
                    , maxmin: true
                    , area: area   // 宽高
                    , btn: ['关闭']
                });
            }
            if (layEvent === 'del') {
                layer.confirm('确定作废凭证吗？', function (index) {
						  //执行 Ajax 后重载
						  $.ajax({
								type: req.type.post,
								url: BASE_WEB + 'voucher/cancel' + '?id=' + data.id,
								async: false,
								success: function (r) {
									 if (r.code === req.status.ok) {
										  table.reload(tableId);
										  wlbKit.sucessMsg('已作废');
									 } else {
										  wlbKit.errorMsg(r.msg);
									 }
								}
						  });
                });
            }
            if (layEvent === 'open_sign') {
                var lock = false;//用来锁定确认按钮，防止重复提交（默认未锁定）
                //加载框。。转圈圈框
                var tishi = layer.msg('签章服务加载中..', {
                    icon: 16
                    ,shade: 0.3
                    ,time: false
                });
                layer.confirm('确定开启签署流程吗？', function (index) {
                    if (!lock) {
                        lock = true;//锁定
                        //执行 Ajax 后重载
                        $.ajax({
                            type: req.type.post,
                            url: BASE_WEB + 'esign/createSignFlow' + '?id=' + data.id,
                            async: true,
                            success: function (r) {
                                if (r.code === req.status.ok) {
                                    table.reload(tableId);
                                    wlbKit.sucessMsg('已开启');
                                } else {
                                    wlbKit.errorMsg(r.msg);
                                }
                            },
									 done: function (r) {
                                layer.close(tishi);
									 }
                        });
                    }
                });
            }
            if (layEvent === 'sign') {
                var orgId;
                if (data.status == '02'){
                   //供应商签署
                    orgId = data.supplierId;
					 }else if(data.status == '22'){
                    //核心企业签署
                    orgId = data.coreEnterpriseId;
					 }
					 var param = {}
                param.orgId = orgId;
                param.signFlowId = data.signFlowId;
                //加载框。。转圈圈框
                var tishi = layer.msg('签章服务加载中..', {
                    icon: 16
                    ,shade: 0.3
                    ,time: false
                });

                //弹出签署页
					 wlbKit.get(BASE_WEB + 'esign/query/getSignFlowUrl', param, function (r) {
                    //最后数据加载完 让loading层消失
                    layer.close(tishi);
                    var area2 = ["80%","80%"];
                    if (r.code === req.status.ok) {
                        var index = layer.open({
                            type: 2
                            , title: '凭证签署'
                            , content: r.data.url
                            , maxmin: true
                            , area: area2   // 宽高
                            , zIndex: layer.zIndex //重点1
                            , success: function(layero){
                                layer.setTop(layero); //重点2
                            }, end: function (layero){
                                //弹出确认签署框
                                layer.confirm("确定已完成签署吗？", {
                                    btn: ["确定","取消"] //按钮
                                }, function(){
                                    var param = {}
                                    param.id = data.id;
                                    param.flowId = data.signFlowId;
                                    wlbKit.post(BASE_WEB + 'voucher/confirmSign', param, function (r) {
                                        if (r.code === req.status.ok) {
                                            parent.wlbKit.sucessMsg("签署成功");
                                            //刷新列表
                                            table.reload(tableId);
													 }else{
                                            parent.wlbKit.errorMsg(r.msg);
													 }
                                    
                                    })
                                    layer.closeAll('dialog');
                                }, function(){
                                    layer.closeAll('dialog');
                                });
									 }
                        });
						// layer.full(index);
                        console.log(JSON.stringify(r))
                       
                        //window.open(r.data.shortUrl);
                        // table.reload(tableId);
                        // wlbKit.sucessMsg('已开启');
                    } else {
                        wlbKit.errorMsg(r.msg);
                    }
					 })
            }
            if (layEvent === 'send') {
                if (data.bankId == null || data.bankId == '') {
                    parent.wlbKit.sucessMsg("请选择关联银行，选择后不可更改！");
                    wlbKit.get( BASE_WEB + 'voucher/generate/getBankList' + '?compId=' + data.coreEnterpriseId, null, function (r){
                        if (r.code === req.status.ok && r.data.items.length > 0) {
                            layer.open({
                                type: 2
                                , title: '选择银行'
                                , content: BASE_WEB + 'voucher/generate/choice/bankView' + '?compId=' + data.coreEnterpriseId
                                , maxmin: true
                                , area: ['30%', '40%']   // 宽高
                                , btn: ['确定', '取消']
                                , yes: function (index, layero) {
                                    //获取选中的银行id
                                    var bodys = layer.getChildFrame("body", index);
                                    var bankId = bodys.find('#bankSelectId input[name="bank"]:checked ').val();
                                    if(typeof(bankId) == 'undefined' || bankId==null || bankId==''){
                                        wlbKit.errorMsg("请选择银行！");
                                        return false;
                                    }

                                    send(data.id, bankId, data.signFlowId);
                                    // //更新凭证银行
												// var param = {};
                                    // param.id = data.id;
                                    // param.bankId = bankId;
												//
												// wlbKit.post(BASE_WEB + 'voucher/update', param, function (k){
                                    //     if (k.code === req.status.ok){
                                    //         data.bankId = bankId;
                                    //         parent.wlbKit.sucessMsg("关联银行成功！");
                                    //         //刷新列表
                                    //         table.reload(tableId);
                                    //         send(data.id, data.signFlowId);
												// 	 }else{
                                    //         parent.wlbKit.errorMsg("关联银行失败！");
                                    //         return false;
												// 	 }
												// });
                                    layer.close(index);
                                }
                            });
								}else{
                            parent.wlbKit.errorMsg("当前核心企业未关联银行，请先进行银行关联！")
                            return false;
                            return;
								}
						  });
        
					 }else{
                    send(data.id, data.bankId, data.signFlowId);
					 }
                // if (data.bankId == null || data.bankId == '') {
                //     return false;
					 // }
            
              
            }
            if (layEvent === 'audit') {
                layer.open({
                    type: 2
                    , title: '审核'
                    //, content: BASE_WEB + 'voucher/detail' + '?id=' + data.id
                    , content: BASE_WEB + 'data/preview' + '?id=' + data.id + '&templateId=' + data.templateId + '&url=voucher/get'
                    , maxmin: true
                    , area: area   // 宽高
                    , btn: ['审批','关闭']
                    , yes: function (index, layero) {
                        layer.open({
										//formType: 2,//这里依然指定类型是多行文本框，但是在下面content中也可绑定多行文本框
                            title: '请选择审批结果',
                            area: ['60%', '40%'],
                            btnAlign: 'c',
                            closeBtn:'1',//右上角的关闭
                            content: '<div><p>审批结果:</p><textarea name="txt_remark" id="remark" placeholder="请输入审批结果" style="width:100%;height:80px;"></textarea></div>' +
										  '<div>' +
										  '<table class="layui-table" id="auditTable" lay-filter="auditTable">' +
										  '</table>' +
										  '</div>' +
										  '',
                            btn:['通过','拒绝','取消'],
									 success: function (index, layero){
                                table.render($.extend(config.layui.table, {
												elem: '#auditTable'
												// ,height: 300
												// ,width:'100%'
												,url: BASE_WEB + 'voucher/audit/list/data?id=' + data.id //数据接口
												,page: true //开启分页
												,cols: [[ //表头
													 {field: 'name', title: '审批人', width:150}
                                        ,{field: 'status', title: '审批结果', width:150, templet: function (d){
																if (d.status == '1'){
																	 return '<span class="layui-badge-rim">审批通过</span>';
																}else{
                                                    return '<span class="layui-badge-rim">审批拒绝</span>';
																}
                                        }}
                                        ,{field: 'auditDate', title: '审批时间', width:220}
                                        ,{field: 'remark', title: '审批描述'}
													 // ,{field: 'detail', title: '描述', width:330}
													 // ,{field: 'id', title: 'ID', width:200,hide:true}
												]]
                            	}));
									 },
                            yes: function (index, layero) {
                                parent.layer.msg('审批通过', {icon: 1});
                                var remark = $('#remark').val();//获取多行文本框的值
                                if (remark == '') {
                                    remark = '审批通过';
                                }
                                audit(data.id, '1', remark);
                                layer.closeAll();
                                table.reload(tableId);
                                //layer.close(index);
										//可执行确定按钮事件并把备注信息（即多行文本框值）存入需要的地方
                            },
                            btn2:function(index){
                                parent.layer.msg('审批拒绝', {icon: 2});
                                var remark = $('#remark').val();//获取多行文本框的值
										  if (remark == '') {
										      remark = '审批拒绝';
										  }
                                audit(data.id, '2', remark);
                                layer.closeAll();
                                table.reload(tableId);
										  return false;
                            
                            },
                            btn3:function(index){
                                layer.close(index);
                            }
                        });
                    }
                });
            }

        });

        // 监听查询
        form.on('submit(kTableSearchFilter)', function (obj) {
            var params = obj.field;
            log('seach=', params);//
            tableIns.reload({
                where: params,
                page: {curr: 1}
            });
            return false;
        });

        // 绑定监听回车事件
        wlbKit.bindEnterEventForLayuiForm();

    });

    /**
	  * 审核凭证
     * @param id 凭证id
     * @param status 凭证状态
     * @param remark 备注
     */
    function audit(id, status, remark){
        var params = {};
        params.id = id;
        params.status = status;
        params.remark = remark;
        wlbKit.post(BASE_WEB + 'voucher/audit', params, function (r) {
            if (r.code === req.status.ok) {
                parent.wlbKit.sucessMsg('审批成功');
            } else {
                parent.wlbKit.errorMsg(r.msg);
            }
		  });
	 }

    /**
	  * 凭证发送
     * @param id 凭证id
     * @param flowId 签章流程id
     */
	 function send(id, bankId, flowId){
        //加载框。。转圈圈框
        var tishi = layer.msg('发送前数据校验中.......', {
            icon: 16
            ,shade: 0.3
            ,time: false
        });
        var param = {}
        param.signFlowId = flowId;
        //先获取签署流程
        wlbKit.get(BASE_WEB + 'esign/query/getSignFlow', param, function (r) {
            layer.close(tishi);
            if (r.code === req.status.ok) {
                if ('2' == r.data.flowStatus){
                    //流程已完成，修改凭证状态
                    var param = {}
                    param.id = id;
                    layer.open({
                        type: 2
                        , title: '凭证发送'
                        //, content: BASE_WEB + 'voucher/detail' + '?id=' + data.id
                        , content: BASE_WEB + 'voucher/sendView?id=' + id + '&bankId=' + bankId
                        , maxmin: true
                        , area: ['70%', '60%']   // 宽高
                        , btn: ['确定', '关闭']
                        , yes: function (index, layero) {
                            layer.confirm("确定将凭证发送银行吗？", {
                                btn: ["确定","取消"] //按钮
                            }, function(){
                                if(!$(".layui-layer-btn0").hasClass("layui-btn-disabled")){
                                    //$(".layui-layer-btn0")这个是确定按钮
                                    $(".layui-layer-btn0").addClass("layui-btn-disabled");
                                    layer.close(index);
                                    layer.msg('处理中...',{shade:[0.8, '#393D49'],time:60*60*1000});

                                    //点击确认触发 iframe 内容中的按钮提交
                                    var submit = layero.find('iframe').contents().find("#kFormSubmit");
                                    submit.click();
                                    layer.closeAll('dialog');//取消按钮
                                }
                            }, function(){
                                layer.closeAll('dialog');//取消按钮
                            });
                        }
                    });
                    // wlbKit.post(BASE_WEB + 'voucher/send', param, function (r) {
                    //     //刷新列表
                    //     table.reload(tableId);
                    // })
                }else {
                    wlbKit.errorMsg("当前签署流程还未完成，不能发送！");
                }
                // layer.closeAll('dialog');
            } else {
                wlbKit.errorMsg(r.msg);
            }
        })
	 }
</script>

</body>
</html>